<template>
  <div class="search-suggestion">
    <van-cell 
    v-for="(text,index) in suggestions"
    :key="index"
    icon="search"
    @click="$emit('search',text)"
    >
    <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import {getSearchSuggestions} from '@/api/search'
import {debounce} from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText:{
      type:String,
      required:true
    }
  },
  data () {
    return {
      suggestions:[] //联想建议数据列表
    }
  },
  computed: {},
  watch: {
    searchText:{
      handler: debounce(function(value){
         this.loadSearchSuggestions(value)
      },500),
      // handler(value){
      //   this.loadSearchSuggestions(value)
      //   console.log(value);
      // },
       immediate:true //该回调将在侦听开始之后被立即调用
    }
  },
  created () {},
  mounted () {},
  methods: {
    async loadSearchSuggestions(q) {
      try{
        const {data} = await getSearchSuggestions(q)
        this.suggestions=data.data.options
      }catch(err){
        console.log(err);
      }
    },
    // 关键字高亮
    highlight(text){
      const highlightStr=`<span style="color:red;">${this.searchText}</span>`
      const reg=new RegExp(this.searchText,'gi')
       return text.replace(reg,highlightStr)
    }
  }
}
</script>

<style scoped lang="less"></style>